package com.smilive.start.netty.chat.server;

import com.smilive.start.netty.chat.peotocol.MessageCodecSharable;
import com.smilive.start.netty.chat.peotocol.ServerChannelDuplexHandler;
import com.smilive.start.netty.chat.peotocol.ProtocolFrameDecoder;
import com.smilive.start.netty.chat.server.handler.LoginRequestMessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @program: netty
 * @Date: 2022-01-06 14:18
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class ChatServer {

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup work = new NioEventLoopGroup();
        //抽取线程安全的Handler,减少类的创建
        LoggingHandler LOG_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MAG_HANDLER = new MessageCodecSharable();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ServerBootstrap bootstrap = serverBootstrap.channel(NioServerSocketChannel.class)
                    .group(boss, work)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 用于空闲连接的检测，5s内未读到数据，会触发READ_IDLE事件
                            ch.pipeline().addLast(new IdleStateHandler(10,0,0));
                            // 添加双向处理器，负责处理READER_IDLE事件
                            ch.pipeline().addLast(new ServerChannelDuplexHandler());
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(LOG_HANDLER);
                            ch.pipeline().addLast(MAG_HANDLER);
                            ch.pipeline().addLast(new LoginRequestMessageHandler());
                        }
                    });
            Channel channel = bootstrap.bind(new InetSocketAddress(8000)).sync().channel();
            channel.closeFuture().sync();
        }catch (Exception e){
            log.error("server error",e);
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }


    }

}
